package com.huluobo.a2204parkdemo.news

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204parkdemo.R
import com.huluobo.a2204parkdemo.databinding.ActivityAddNewsBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class AddNewsActivity : BaseActivity<ActivityAddNewsBinding, NewsViewModel>() {
    override fun initData() {
        viewModel.addNewsSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

    override fun initView() {
        binding.addNewsHeader.headerTitle.text = "添加新闻"
        binding.addNewsHeader.headerBack.setOnClickListener { finish() }

        binding.addNewsCommit.setOnClickListener {
            val time = getTime()
            val newsTitle = binding.addNewsTitleEt.text.toString()
            val newsValue = binding.addNewsValueEt.text.toString()
            if (newsTitle.isNotEmpty() && newsValue.isNotEmpty()) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_NEWS_TITLE] = newsTitle
                map[Const.PARAM_NEWS_VALUE] = newsValue
                map[Const.PARAM_NEWS_TIME] = time

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.addNews(body)
            } else {
                ToastUtils.showLong("新闻内容不能为空")
            }
        }
    }
}